<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class M_user_open_sy extends MY_Model {
	
	protected $_table = "user_open_sy";
	protected $_uid = "id";

	public function __construct(){
		parent::__construct();
	}

	public function get_user_profile()
	{
		$user_id = $this->c_user->userid;
		$sy = $this->_get_user_profile($user_id);
		
		
		if($sy === false){

			/** IF RECORD DO NOT EXIST CREATE RECORD FIRST BASED ON THE SYSTEM CURRENT SCHOOL YEAR **/
			$this->load->model('M_school_years');
			$c_sy = $this->M_school_years->get_school_year_set();
			if($c_sy){
				
				unset($data);
				$data['user_id'] = $user_id;
				$data['sy_id'] = $c_sy->id;
				if($user_id){
					$xrs_add = $this->insert($data); //Insert data
					if($xrs_add){
						return $this->_get_user_profile($user_id); //return add record
					}
				}
			}
		}

		return $sy;
	}	

	private function _get_user_profile($user_id)
	{
		unset($get);
		$get['fields'] = array(
				'school_years.*',
				'user_open_sy.id as user_open_sy_id'
			);
		$get['where']['user_open_sy.user_id'] = $user_id;
		$get['single'] = true;
		$get['join'][] = array(
				'table' => 'school_years',
				'on' => 'user_open_sy.sy_id = school_years.id',
				'type' => 'left'
			);

		return $this->get_record(false, $get);
	}

	public function set_user_school_year($sy_id)
	{
		$ct = $this->M_user_open_sy->get_user_profile($this->c_user->userid);
		unset($data);
		$data['sy_id'] = $sy_id;
		$rs = $this->update(array('user_id' => $this->c_user->userid), $data);
		return $rs;
	}
}